import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/refund_order_list_entity.dart';
import 'package:taonile/utils/event_msg.dart';
import 'package:taonile/utils/singleton_manager.dart';

import '../entity/order_list_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';
import '../views/default_views.dart';
import '../views/dialog_manager.dart';
import 'package:crypto/crypto.dart';

class OrderRefundListPage extends StatefulWidget {
  const OrderRefundListPage({Key? key}) : super(key: key);

  @override
  State<OrderRefundListPage> createState() => _OrderRefundListPageState();
}

class _OrderRefundListPageState extends State<OrderRefundListPage> {
  List<RefundOrderListData> datas = [];
  var page = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getOrderList();

    SingletonManager.instance.eventBus.on<RefundListUp>().listen((event) {
      print('刷新一下下退款单列表');
      page = 1;
      getOrderList();
    });
  }

  getOrderList() async {
    dynamic result = await Api.refundOrderList({'page': page.toString(), 'size': '20'});
    RefundOrderListEntity entity = RefundOrderListEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  getSkuStr(List<RefundOrderListDataSkuData> currentSku) {
    StringBuffer sb = StringBuffer();
    for (int i = 0; i < currentSku.length; i++) {
      sb.write(currentSku[i].skuVal);
      if (i != currentSku.length - 1) {
        sb.write('/');
      }
    }
    return sb.toString();
  }

  getTypeName(int type) {
    if (type == 1) {
      return '退款';
    } else if (type == 2) {
      return '退货退款';
    } else {
      return '补发商品';
    }
  }

  Widget getOrderItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.refundOrderDetail, params: {
          'orderNo': datas[index].id.toString(),
          'isShowExpress': datas[index].isShowExpress.toString()
        }).then((value) {});
      },
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 10.w, horizontal: 25.w),
        padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
        decoration: BoxDecoration(
          color: (Config.colorWhite),
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    datas[index].storeName,
                    style: TextStyle(fontSize: 24.sp),
                  ),
                ),
                Text(
                  getTypeName(datas[index].type),
                  style: TextStyle(fontSize: 22.sp, color: Colors.red),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: 20.w),
            ),
            Container(
              height: 140.w,
              width: double.infinity,
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                padding: EdgeInsets.symmetric(vertical: 1.w),
                itemCount: 1,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index2) {
                  return getProductItem(datas[index]);
                },
              ),
            ),
            Padding(
              padding: EdgeInsets.only(top: 5.w),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  datas[index].retreatTitle,
                  style: TextStyle(fontSize: 23.sp, color: Colors.red),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 15.w),
                ),
                Text(
                  datas[index].retreatDetails,
                  style: TextStyle(fontSize: 23.sp, color: Config.colorText1),
                ),
              ],
            ),
            Divider(
              color: Config.colorDivider,
              height: 38.w,
              thickness: 2.w,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Visibility(
                  visible: datas[index].isShowExpress == 1 && datas[index].type == 2,
                  child: Container(
                    margin: EdgeInsets.only(left: 15.w),
                    width: 160.w,
                    height: 46.w,
                    child: ElevatedButton(
                      clipBehavior: Clip.antiAlias,
                      onPressed: () => {
                        Routes.navigateTo(context, Routes.refundOrderDetail, params: {
                          'orderNo': datas[index].id.toString(),
                          'isShowExpress': datas[index].isShowExpress.toString()
                        }).then((value) {})
                      },
                      style: ButtonStyle(
                        elevation: MaterialStateProperty.all(0),
                        backgroundColor: MaterialStateProperty.all(Colors.white),
                        shape: MaterialStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(24.w),
                          ),
                        ),
                        side: MaterialStateProperty.all(
                          BorderSide(color: Config.colorText3, width: 2.w),
                        ),
                      ),
                      child: Text(
                        '填写运单号',
                        style: TextStyle(fontSize: 18.sp, color: Config.colorText3),
                      ),
                    ),
                  ),
                ),
                Visibility(
                  visible: true,
                  child: Container(
                    margin: EdgeInsets.only(left: 15.w),
                    width: 140.w,
                    height: 46.w,
                    child: ElevatedButton(
                      clipBehavior: Clip.antiAlias,
                      onPressed: () => {},
                      style: ButtonStyle(
                        elevation: MaterialStateProperty.all(0),
                        backgroundColor: MaterialStateProperty.all(Colors.white),
                        shape: MaterialStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(24.w),
                          ),
                        ),
                        side: MaterialStateProperty.all(
                          BorderSide(color: Config.colorText3, width: 2.w),
                        ),
                      ),
                      child: Text(
                        '删除记录',
                        style: TextStyle(fontSize: 18.sp, color: Config.colorText3),
                      ),
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget getProductItem(RefundOrderListData item) {
    return Container(
      height: 120.w,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            margin: EdgeInsets.only(right: 20.w),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(5),
              child: CachedNetworkImage(
                imageUrl: CommonUtils.compressImageUrl(item.imgPath, 150, 150),
                fit: BoxFit.fill,
                width: 100.w,
                height: 100.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: 100.w,
                    height: 100.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(top: 8.w),
              ),
              Container(
                width: 540.w,
                child: Text(
                  item.goodsName,
                  softWrap: false,
                  style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                ),
              ),
              Container(
                width: 540.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      getSkuStr(item.skuData),
                      softWrap: true,
                      style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                    ),
                    Text(
                      "X${item.num}",
                      softWrap: true,
                      style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 12.w),
              ),
              Text(
                '${item.totalPrice}金券',
                softWrap: true,
                style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('退款售后'),
        centerTitle: true,
      ),
      body: datas.isNotEmpty
          ? Container(
              width: double.infinity,
              height: double.infinity,
              child: EasyRefresh(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  await Future.delayed(const Duration(milliseconds: 200), () {
                    page = 1;
                    getOrderList();
                  });
                },
                onLoad: () async {
                  getOrderList();
                },
                child: ListView.builder(
                  // shrinkWrap: true,
                  // scrollDirection: Axis.vertical,
                  // physics: const BouncingScrollPhysics(),
                  padding: EdgeInsets.symmetric(vertical: 5.w),
                  itemCount: datas.length,
                  itemBuilder: (BuildContext context, int index) {
                    return getOrderItem(index);
                  },
                ),
              ),
            )
          : showNullData(),
    );
  }
}
